<?php

namespace App\Models\Cruise;

use App\Models\BaseModel;
use App\Models\Common\ResourcesModel;
use App\Models\Traits\KfUid;
use Illuminate\Support\Collection;

class CruiseCheckRectifyReplyModel extends BaseModel
{
    use KfUid;

    protected $table    = 'cruise_check_rectify_reply';
    protected $fillable = [
        'cruiseCheckRectifyId',
        'desc',
        'rejected',
    ];

    const IS_COMMON   = 0; // 正常
    const IS_REJECTED = 1; // 被驳回

    /**
     * 批量获取整改内容
     * @param array $cruiseCheckRectifyIds
     */
    public static function getDataByRectifyIds(array $cruiseCheckRectifyIds)
    {
        // replyModels
        $replyModels = self::query()
                           ->whereIn('cruiseCheckRectifyId', $cruiseCheckRectifyIds)
                           ->where('rejected', self::IS_COMMON)
                           ->get();

        $replyIds = $replyModels->pluck('id')->toArray();

       return self::getDataByIds($replyIds, $replyModels)->keyBy('cruiseCheckRectifyId');
    }

    /**
     * 批量通过id获取整改内容
     * @param array $ids
     * @param Collection|null $replyModels
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|Collection
     */
    public static function getDataByIds(array $ids, ?Collection $replyModels = null)
    {
        if (!$replyModels) {
            $replyModels =  self::query()
                                ->whereIn('id', $ids)
                                ->where('rejected', self::IS_COMMON)
                                ->get();
        }

        // 涉及到的resources
        $files = ResourcesModel::query()
                               ->where('module', ResourcesModel::MODULE_TYPE_CHECK)
                               ->where('business', ResourcesModel::BUSINESS_CHECK_RECTIFY_FILES)
                               ->whereIn('businessId', $ids)
                               ->get()
                               ->map(function ($item) {
                                   return [
                                       'businessId' => $item->businessId,
                                       'url'        => $item->url,
                                       'type'       => $item->extraArr['type'] ?? '',
                                   ];
                               })->groupBy('businessId')->toArray();

        return $replyModels->map(function ($item) use ($files) {

            return [
                'id'                   => $item->id,
                'cruiseCheckRectifyId' => $item->cruiseCheckRectifyId,
                'desc'                 => $item->desc,
                'rejected'             => $item->rejected,
                'files'                => $files[$item->id] ?? [],
            ];
        })->keyBy('id');
    }
}
